package bot;

import model.Hand;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Bot extends Thread{

    private Socket socket = null;
    public PrintWriter out = null;
    private BufferedReader in = null;
    private String line = "";
    private String name;
    private String shortName;
    //Bot fields

    private int round;
    private int stake;
    private int maxBet;

    private int[] botHand;
    private String reducedHandSet;
    private int reducedHandLength;
    private int reducedHandWorstCardRank;

    private int botStartingCoins = -1;
    private int botCoins;
    private int botBet;
    private PlayerInfo[] arrayOfPlayers;
    private int numbersOfAddedPlayers = 0;
    private String temp = "";

    public Bot(int port, String IP, String name) {
        this.name = name;
        shortName = name.trim();
        arrayOfPlayers = new PlayerInfo[5];
        botHand = new int[4];
        try {
            this.socket  = new Socket(IP,port);
        }
        catch (IOException e){
            System.out.println("Socket problem");
            System.exit(1);
        }
    }
    private void performAction(String enabledButtons) {
        try {
            sleep(2000);
        }catch (InterruptedException e) {
        	System.out.println("InterruptedException in performAction");
        }
        
        if (enabledButtons.equals("CF")) {
            temp = "Call_";
        }
        else if (enabledButtons.equals("HRF")) {
            temp = "Check_";
        }
        else if (enabledButtons.equals("CRF")) {
            if (reducedHandLength == 4 || (reducedHandLength == 3 && reducedHandWorstCardRank <7))
                temp = ("Call_" +  Integer.toString(maxBet + 10));
            else
                temp = ("Fold_");
        }
        else if (enabledButtons.equals("FA")) {
            temp = ("Fold_");
        }
        else if (enabledButtons.equals("RF")) {
            if (reducedHandLength == 4 || (reducedHandLength == 3 && reducedHandWorstCardRank <7))
                temp = ("Raise_" +  Integer.toString(maxBet + 10));
            else
                temp = ("Fold_");
        }
        else if (enabledButtons.equals("HBF")) {
            temp = ("Check_");
        }
        else if (enabledButtons.equals("HF")) {
            temp = ("Check_");
        }
        else if (enabledButtons.equals("E")) {
            System.out.println("** Changed cards: " + getCardSetForExhange(reducedHandSet) + " **");
            temp = ("Exchange_" + getCardSetForExhange(reducedHandSet));
        }
        System.out.println("Bot sends: " + temp);
        out.println(temp);
    }
    public String getCardSetForExhange(String cards) {
        String cardSet = "";
        while (!cards.equals("")) {
            if (cards.startsWith("1")) {
                cardSet += 0;
            }
            else if (cards.startsWith("0")) {
                cardSet += 1;
            }
            cards = cards.substring(1);
        }
        return cardSet;
    }
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println("Name_" + name);
        }
        catch (IOException e){
            System.out.println("or out failed");
        }

        while (line != null) {
            try {
                line = in.readLine();
                System.out.println("!!** GOT LINE: " + line + " **!!");
                if (line.startsWith("addNewPlayer")) {
                    arrayOfPlayers[numbersOfAddedPlayers] = new PlayerInfo(line.substring(12));
                    System.out.println("** Adding player number: " + numbersOfAddedPlayers + " **");
                    numbersOfAddedPlayers++;
                }
                else if (line.startsWith("Accepted_")) {
                    out.println("Name_"+name);
                }
                else if (line.startsWith("BadName_")) {
                    System.out.println("Name \"" + shortName +"\" is already used");
                    System.exit(1);
                }
                else if (line.startsWith("previousPlayers_")) {
                    line = line.substring(16);
                    String temp;
                    while(!line.equals("")){
                        temp = line.substring(0, 15);
                        line = line.substring(15);
                        arrayOfPlayers[numbersOfAddedPlayers] = new PlayerInfo(temp);
                        System.out.println("** Adding player number: " + numbersOfAddedPlayers + " **");
                        numbersOfAddedPlayers++;
                    }
                }
                else if (line.startsWith("SmallBlind_")) {
                    String playerName = line.substring(11, 26);
                    String blind = line.substring(26);
                    if (playerName.equals(name)) {
                        botBet = Integer.parseInt(blind);
                    }
                    else {
                        int i;
                        for(i = 0; !(arrayOfPlayers[i].getName().equals(playerName)); i++) {
                            if(i > 5) {
                                System.out.println("ERROR");
                                break;
                            }
                        }
                        arrayOfPlayers[i].setSmallBlind(true);
                        arrayOfPlayers[i].setCurrentBet(Integer.parseInt(blind));

                    }
                }
                else if (line.startsWith("BigBlind_")) {
                    String playerName = line.substring(9, 24);
                    String blind = line.substring(24);
                    int bBlind = Integer.parseInt(blind);
                    maxBet = bBlind;
                    if(playerName.equals(name)) {
                        botBet = bBlind;
                    }
                    else {
                        int i;
                        for(i = 0; !(arrayOfPlayers[i].getName().equals(playerName)); i++) {
                            if(i > 5) {
                                System.out.println("ERROR");
                                break;
                            }
                        }
                        arrayOfPlayers[i].setBigBlind(true);
                        arrayOfPlayers[i].setCurrentBet(Integer.parseInt(blind));
                    }
                }
                else if (line.startsWith("Cards_")) {
                    System.out.print("** ");
                    for (int i = 0; i < 4; i++) {
                        botHand[i] = Integer.parseInt(line.substring(6+2*i, 8+2*i));
                        System.out.print(botHand[i]);
                    }
                    System.out.println(" **");
                    reducedHandLength = Hand.getReducedHand(botHand).length;
                    reducedHandSet = Hand.getReducedHandCardSet(botHand);
                    reducedHandWorstCardRank = Hand.giveWorstCard(Hand.getReducedHand(botHand));
                    System.out.println("** Reduced Hand Set: " + reducedHandSet + " **");
                }
                else if (line.startsWith("sCoins_")) {
                    String playerName = line.substring(7, 22);
                    String amount = line.substring(22);
                    if (playerName.equals(name)) {
                        if (botStartingCoins == -1) {
                            botStartingCoins = Integer.parseInt(amount);
                            System.out.println("** Starting Coins = " + botStartingCoins + " **");
                        }
                        botCoins = Integer.parseInt(amount);
                    }
                    else {
                        int i;
                        for (i = 0; !(arrayOfPlayers[i].getName().equals(playerName)); i++) {
                            if (i > 5) {
                                System.out.println("ERROR");
                                break;
                            }
                        }
                        arrayOfPlayers[i].setTotalCoins(Integer.parseInt(amount));
                    }
                }
                else if ( line.startsWith("Bet_")) {
                    String playerName = line.substring(4, 19);
                    int bet = Integer.parseInt(line.substring(19));
                    if(bet > maxBet) {
                        maxBet = bet;
                    }
                    if (playerName.equals(name)) {
                        botBet = bet;
                    }
                    else {
                        int i;
                        for (i = 0; !(arrayOfPlayers[i].getName().equals(playerName)); i++) {
                            if (i > 5) {
                                System.out.println("ERROR");
                                break;
                            }
                        }
                        arrayOfPlayers[i].setValueOfRise(maxBet - bet);
                        System.out.println(arrayOfPlayers[i].getName() + " rised " + (maxBet - bet));
                        arrayOfPlayers[i].setCurrentBet(bet);
                    }
                }
                else if (line.startsWith("Enable_")) {
                    performAction(line.substring(7));
                }
                else if (line.startsWith("dFold_")) {
                    String playerName = line.substring(6);
                    if (!playerName.equals(name)) {
                        int i;
                        for (i = 0; !(arrayOfPlayers[i].getName().equals(playerName)); i++) {
                            if (i > 5) {
                                System.out.println("ERROR");
                                break;
                            }
                        }
                        arrayOfPlayers[i].setFolded(true);
                    }
                }
                else if (line.startsWith("dAllin_")) {
                    String playerName = line.substring(7);
                    if (!playerName.equals(name)) {
                        int i;
                        for (i = 0; !(arrayOfPlayers[i].getName().equals(playerName)); i++) {
                            if (i > 5) {
                                System.out.println("ERROR");
                                break;
                            }
                        }
                        arrayOfPlayers[i].setAllIn(true);
                    }
                }
                else if (line.startsWith("Stake_")) {
                    stake = Integer.parseInt(line.substring(6));
                }
                else if (line.startsWith("Round_")) {
                    round = Integer.parseInt(line.substring(6));
                }
                else if (line.startsWith("Delete_")) {
                }
                else if (line.startsWith("Amount_")) {
                    String playerName = line.substring(7, 22);
                    int amountOfChangedCards = Integer.parseInt(line.substring(22));
                    if (!playerName.equals(name)) {
                        int i;
                        for (i = 0; !(arrayOfPlayers[i].getName().equals(playerName)); i++) {
                            if (i > 5) {
                                System.out.println("ERROR");
                                break;
                            }
                        }
                        arrayOfPlayers[i].setRecentlyChangedCards(amountOfChangedCards);
                    }
                }
                else if(line.startsWith("Winner_")) {
                	try
					{
						sleep(1000);
					} catch (InterruptedException e){}
                	String temp2=("Close_");
                    System.out.println("Bot send: " +temp2);
                    out.println(temp2);
                    
                }
                else if (line.startsWith("Info_")) {
					try
					{
						sleep(1000);
					} catch (InterruptedException e){}
                    System.out.println(line + "\nBot send: End_");
                    out.println("End_");
                    System.exit(1);
				}

            }
            catch(IOException e){
                System.out.println("Read failed");
                System.exit(1);
            }
        }
    }


}
